﻿using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Pdf2epub.BusinessLogic.Extractors.ExtractStrategy;
using Pdf2epub.Interfaces;
using Pdf2epub.Model;

namespace Pdf2epub.BusinessLogic.Extractors
{
    internal class PdfHtmlExtractor : ExtractorBase
    {
        private readonly PdfReader m_PdfReader;
        private readonly IProjectContext m_ProjectContext;
        private readonly HtmlTextExtractionStrategy m_Strategy;

        public PdfHtmlExtractor(IProjectContext projectContext, string pdfPath)
            : base(projectContext)
        {
            m_ProjectContext = projectContext;

            m_PdfReader = new PdfReader(pdfPath);

            m_Strategy = new HtmlTextExtractionStrategy(m_ProjectContext);
            m_Strategy.CurrentOperatingMode = OperatingMode.Extract;
            m_Strategy.ImagePath = m_ProjectContext.ProjectConfiguration.ImageOutputPath;
        }

        public override int NumberOfPages
        {
            get { return m_PdfReader.NumberOfPages; }
        }

        public override Chapter[] ExtractDocumentOutline()
        {
            PdfOutlineExtraction pdfOutlineExtraction = new PdfOutlineExtraction();
            return pdfOutlineExtraction.Extract(m_PdfReader);
        }

        protected override void ClearImageCounter()
        {
            m_Strategy.ClearImageCounter();
        }

        protected override ContentBlock[] Extract(int page)
        {
            m_Strategy.PreviewMode = true;

            if ((page < 1) || (page > m_PdfReader.NumberOfPages))
                return new ContentBlock[] { };

            m_Strategy.ClearContentBlocks();
            m_Strategy.TakeFirstPictureAsCover = (page == 1);

            PdfTextExtractor.GetTextFromPage(m_PdfReader, page, m_Strategy);

            return m_Strategy.ContentBlocks;
        }

        public ContentBlock[] ExtractPage(int page)
        {
            return Extract(page);
        }
    }
}